const WebSocket = require('ws');

class WebSocketServer {
    static _EventCallBack={};


    constructor() {
        this.port=0;
        this.install();
    }

    set(url, callback) {
        WebSocketServer._EventCallBack[url]=callback;
    }

    listen(port){
        this.port=port;
        let that=this;
        this.server = new WebSocket.Server({port:port});
        console.log('websocket listen on '+ this.port)
        this.server.on('open',function open(){
            WebSocketServer._EventCallBack['open']? WebSocketServer._EventCallBack['open']():console.log('webSocket open on'+ this.port);
        })

        this.server.on('serverClose',function close(){
            WebSocketServer._EventCallBack['serverClose']? WebSocketServer._EventCallBack['serverClose']():console.log(' close');
        })
        this.server.on('connection',function connection(ws,req){
            const ip = req.socket.remoteAddress
            const port = req.socket.remotePort
            req.remoteIp=ip;
            req.remotePort=port;
            ws.remoteIp=ip;
            ws.remotePort=port;
            let res={};
            res.send=function (v){
                if(Array.isArray(v)){
                    v=new Buffer(v)
                }
                ws.send(v)
            }
            res.forword=function (v){
                if(Array.isArray(v)){
                    v=new Buffer(v)
                }
                that.server.clients.forEach(function each(client){
                    if(client.readyState === WebSocket.OPEN && (client.remoteIp !=req.remoteIp || client.remotePort !=req.remotePort )){
                        client.send(buffer)
                    }
                })
            }

            WebSocketServer._EventCallBack['connection']? WebSocketServer._EventCallBack['connection'](req,res):console.log('connection '+ip+" "+port);
            ws.on('message',function incoming(message){
                req.params=message;
                WebSocketServer._EventCallBack['message']? WebSocketServer._EventCallBack['message'](req,res):console.log(' message');
            })

            ws.on('close',function incoming(message){
                WebSocketServer._EventCallBack['close']? WebSocketServer._EventCallBack['close'](req,res):console.log('close '+ ip+" "+port);
            })
        })

    }
    send(buffer) {
        if(Array.isArray(buffer)){
            buffer=new Buffer(buffer)
        }
        this.server.clients.forEach(function each(client){
            if(client.readyState === WebSocket.OPEN){
                client.send(buffer)
            }
        })
    }

    install(app,server){

    }
}

module.exports =  WebSocketServer;